/*
 * Copyright (C) 2010 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.TopBar;
import com.mol.market.common.util.Utils;
import com.mol.market.common.widget.AppListAdapter;
import com.mol.market.common.widget.BaseActivity;
import com.mol.market.common.widget.LoadingDrawable;
import com.mol.market.common.widget.TopGallery;
import com.mol.market.widget.SlotMachinesWidget;

/**
 * 首页
 * 
 * @author andrew.wang
 * @date 2011-5-9
 * @since Version 0.7.0
 */
public class HomeActivity extends BaseActivity implements OnClickListener, OnItemClickListener,
        ApiAsyncTask.ApiRequestListener {

    /* 首页推荐列表*/
    private static final int LOAD_NUM = 50;
    
    private static final int STATUS_INIT = -1;
    private static final int STATUS_OK = 1;
    private static final int STATUS_ERROR = 0;

    private ListView mRecommendList;
    private AppListAdapter mRecommendAdapter;
    private FrameLayout mLoading;
    private ProgressBar mProgress;
    private TextView mNoData;
    private int mIsToLoaded = STATUS_INIT;
    private int mIsBottomLoaded = STATUS_INIT;
    private ArrayList<HashMap<String, Object>> mTopData;
    private ArrayList<HashMap<String, Object>> mBottomData;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_home_layout);

        @SuppressWarnings("unchecked")
        HashMap<String, Object> item = (HashMap<String, Object>) getIntent().getSerializableExtra(
                Constants.EXTRA_HOME_DATA);
        
        initDataForWidget();
        
        initView(item);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
//        TCAgent.onResume(getParent());
    }

    @Override
    protected void onPause() {
        super.onPause();
//        TCAgent.onPause(getParent());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /*
     * 初始化Topbar
     */
    private void initTopBar() {

        int isShowRebate;
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD) {
            isShowRebate = View.GONE;
        } else {
            isShowRebate = View.VISIBLE;
        }
        TopBar.createTopBar(
                mSession,
                this, 
                new View[] { 
                    findViewById(R.id.logo), 
                    findViewById(R.id.top_bar_search),
//                    findViewById(R.id.top_bar_rebate)
                },
                new int[] { 
                    View.VISIBLE, 
                    View.VISIBLE,
//                    isShowRebate
                },
                "");
    }

    @SuppressWarnings("unchecked")
    private void initView(HashMap<String, Object> item) {
        
        mRecommendList = (ListView) findViewById(android.R.id.list);
        mLoading = (FrameLayout) findViewById(R.id.loading);
        mProgress = (ProgressBar) findViewById(R.id.progressbar);
        mProgress.setIndeterminateDrawable(new LoadingDrawable(getApplicationContext()));
        mProgress.setVisibility(View.VISIBLE);
        mNoData = (TextView) findViewById(R.id.no_data);
        mNoData.setOnClickListener(this);
        mRecommendList.setEmptyView(mLoading);
        
        if (item != null) {
            handleTopContent((ArrayList<HashMap<String, Object>>) item
                    .get(Constants.EXTRA_HOME_DATA_TOP));
            handleBottomContent((ArrayList<HashMap<String, Object>>) item
                    .get(Constants.EXTRA_HOME_DATA_BOTTOM));
        } else {
            initData();
        }
    }
    
    /*
     * 获取首页推荐内容
     */
    private void initData() {
        // reset the loading flag
        MarketAPI.getHomeMasterRecommend(getApplicationContext(), this);
        MarketAPI.getHomeRecommend(getApplicationContext(), this, 0, LOAD_NUM, false);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public void onSuccess(int method, Object obj) {

        switch (method) {
        case MarketAPI.ACTION_GET_HOME_MASTER_RECOMMEND:
            
            handleTopContent((ArrayList<HashMap<String, Object>>) obj);
            break;
            
        case MarketAPI.ACTION_GET_HOME_RECOMMEND:
            
            handleBottomContent((ArrayList<HashMap<String, Object>>) ((HashMap<String, Object>) obj)
                    .get(Constants.KEY_PRODUCT_LIST));
            break;
            
        default:
            break;
        }
    }

    @Override
    public void onError(int method, int statusCode) {
        
        switch (method) {
        case MarketAPI.ACTION_GET_HOME_MASTER_RECOMMEND:

            if (statusCode == ApiAsyncTask.BUSINESS_ERROR) {
                // 没有顶部推荐产品
                mTopData = null;
                mIsToLoaded = STATUS_OK;
                bindAdapter();
            } else {
                mIsToLoaded = STATUS_ERROR;
                mNoData.setVisibility(View.VISIBLE);
                mProgress.setVisibility(View.GONE);
            }
            
            break;
            
        case MarketAPI.ACTION_GET_HOME_RECOMMEND:
            mIsBottomLoaded = STATUS_ERROR;
            mNoData.setVisibility(View.VISIBLE);
            mProgress.setVisibility(View.GONE);
            break;
            
        }
    }
    
    private void handleTopContent(ArrayList<HashMap<String, Object>> result) {
        
        if (result == null || result.size() == 0) {
            return;
        }
        
        HashMap<String, Object> item = new HashMap<String, Object>();
        item.put(Constants.KEY_ID, null);
        item.put(Constants.KEY_ICON_URL, R.drawable.app_icon);
        item.put(Constants.KEY_RECOMMEND_NAME, getString(R.string.sort_install_nessary_title));
        item.put(Constants.KEY_PIC_URL, R.drawable.install_topic);
        if (mSession.isFirstLogin()) {
            // 首次进入，装机必备放在首页
            result.add(0, item);
        } else {
            result.add(item);
        }
        
        mTopData = result;
        mIsToLoaded = STATUS_OK;
        bindAdapter();
    }
    
    private void handleBottomContent(ArrayList<HashMap<String, Object>> result) {
        
        if (result == null || result.size() == 0) {
            return;
        }
        

        mBottomData = result;
        mIsBottomLoaded = STATUS_OK;
        bindAdapter();
    }
    
    private void bindAdapter() {
        
        if (mIsToLoaded != STATUS_OK) {
            return;
        }
        if (mIsBottomLoaded != STATUS_OK) {
            return;
        }
        
        // bind the top data
        if ((mTopData != null) && 
                (mRecommendList.getHeaderViewsCount() == 0)) {
            TopGallery gallery = new TopGallery(this, mRecommendList, mTopData);
            mRecommendList.addHeaderView(gallery.getView(), null, false);
        }
        
        // bind the bottom data
        mRecommendAdapter = new AppListAdapter(
                getApplicationContext(),
                mBottomData,
                R.layout.common_product_list_item, 
                new String[] {
                        Constants.KEY_PRODUCT_ICON_URL, 
                        Constants.KEY_PRODUCT_NAME,
                        Constants.KEY_PRODUCT_SUB_CATEGORY, 
                        Constants.KEY_PRODUCT_IS_STAR,
                        Constants.KEY_PRODUCT_SIZE, 
                        Constants.KEY_PRODUCT_DOWNLOAD }, 
                new int[] {
                        R.id.iv_logo, 
                        R.id.tv_name, 
                        R.id.tv_description, 
                        R.id.iv_star,
                        R.id.tv_size, 
                        R.id.tv_download });
        mRecommendAdapter.setActivity(getParent());
        
        mRecommendAdapter.setProductList();
        mRecommendList.setAdapter(mRecommendAdapter);
        mRecommendList.setOnItemClickListener(this);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        switch (parent.getId()) {
        case android.R.id.list:

            // 首页产品列表，去产品详细页 需要考虑Header View所占位置
            HashMap<String, Object> item = (HashMap<String, Object>) mRecommendAdapter
                    .getItem(position - mRecommendList.getHeaderViewsCount()); 
            String pid = (String) item.get(Constants.KEY_PRODUCT_ID);
            boolean isCpa = (Boolean) item.get(Constants.KEY_PRODUCT_IS_STAR);
            Intent detailIntent = new Intent(getApplicationContext(), com.mol.market.ui_v4.ProductDetailActivity.class);
            detailIntent.putExtra(Constants.EXTRA_PRODUCT_ID, pid);
            
            if (isCpa) {
                // 统计推荐位
                Utils.trackEvent(
                        getApplicationContext(),
                        Constants.GROUP_2,
                        String.format(Constants.EVENT_CLICK_RECOMMEND,
                                item.get(Constants.KEY_PRODUCT_NAME), position));
                detailIntent.putExtra(Constants.EXTRA_PRODUCT_RECOMMEND, true);
            }
            startActivity(detailIntent);
            
            break;

        default:

            break;
        }
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return getParent().onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        // 首页重试
        mNoData.setVisibility(View.GONE);
        mProgress.setVisibility(View.VISIBLE);
        
        if (mIsToLoaded == STATUS_ERROR) {
            mIsToLoaded = STATUS_INIT;
            MarketAPI.getHomeMasterRecommend(getApplicationContext(), this);
        }

        if (mIsBottomLoaded == STATUS_ERROR) {
            mIsBottomLoaded = STATUS_INIT;
            MarketAPI.getHomeRecommend(getApplicationContext(), this, 0, LOAD_NUM, false);
        }
    }
    
    /**
     * 为Widget去请求数据
     */
    private void initDataForWidget(){
        MarketAPI.getHomeRecommend(getApplicationContext(), new ApiAsyncTask.ApiRequestListener() {
            
            @SuppressWarnings("unchecked")
            @Override
            public void onSuccess(int method, Object obj) {
                sendToSlotMachinesWidget((ArrayList<HashMap<String, Object>>) ((HashMap<String, Object>) obj)
                        .get(Constants.KEY_PRODUCT_LIST));
            }
            
            @Override
            public void onError(int method, int statusCode) {
                //do nothing
            }
        }, 51, 100, true);
    }
    /**
     * 将图片信息(url)发送给widget
     * @param list
     */
    private void sendToSlotMachinesWidget(ArrayList<HashMap<String, Object>> list){
        Intent intent = new Intent(SlotMachinesWidget.ACTION_APP);
        intent.putExtra(SlotMachinesWidget.INTENT_APP_INFO, list);
        sendBroadcast(intent);
    }

}